package cn.tedu.medical.passport.service.impl;

import cn.tedu.medical.common.enumerator.ServiceCode;
import cn.tedu.medical.common.ex.ServiceException;
import cn.tedu.medical.passport.dao.persist.repository.IUserRepository;
import cn.tedu.medical.passport.pojo.entity.LoginLog;
import cn.tedu.medical.passport.pojo.param.UserLoginInfoParam;
import cn.tedu.medical.passport.pojo.vo.UserLoginInfoVO;
import cn.tedu.medical.passport.pojo.vo.UserLoginResultVO;
import cn.tedu.medical.passport.service.IUserService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理用户数据的业务实现类
 *
 * @author zyb
 * @version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public UserLoginResultVO login(UserLoginInfoParam userLoginInfoParam, String remoteAddr, String userAgent) {
        log.debug("开始处理[用户登录]的业务参数:{}",userLoginInfoParam);
        String username = userLoginInfoParam.getUsername();
        UserLoginInfoVO LoginInfo = userRepository.getLoginInfoByUsername(username);
        if (LoginInfo==null){
            String message = "登录失败，用户名或密码错误！（开发阶段专用：用户名错误）";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED,message);
        }
        if (!LoginInfo.getEnable().equals(1)){
            String message = "登录失败此账号已被禁用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED_DISABLED,message);
        }
        String password = userLoginInfoParam.getPassword();
        if (!passwordEncoder.matches(password, userLoginInfoParam.getPassword())){
            String message = "登录失败，用户名或密码错误！（开发阶段专用：密码错误）";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED, message);
        }
        Long userId = LoginInfo.getId();
        Integer loginCount = LoginInfo.getLoginCount();
        String avatar = LoginInfo.getAvatar();

        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions =LoginInfo.getPermissions();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        String authoritiesJsonString = JSON.toJSONString(authorities);

        LocalDateTime now = LocalDateTime.now();
        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(userId);
        loginLog.setUsername(username);
        loginLog.setIp(remoteAddr);
        loginLog.setUserAgent(userAgent);
        loginLog.setGmtLogin(now);

        return null;
    }
}
